package com.rexolar.openapi.utlis;

import com.rexolar.openapi.constants.Constants;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

/**
 * @author zhusiyu
 * @description: CommonUtils
 * @date 2020-04-22
 **/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Slf4j
public class CommonUtils {
    private static Map<String, Pattern> regMap = new ConcurrentHashMap<>();
    /**
     * 转换成数字类型版本号
     * @param apiVersion
     * @return
     */
    public static int convertVersion(String apiVersion) {
        if (StringUtils.isEmpty(apiVersion) || Constants.NONE_STRING.equals(apiVersion)) {
            return -1;
        }
        String regex = "[^0-9.]";
        //替换所有 非数字非. 的字符为空  如1.1.0-RELEASE 替换后为1.1.0
        String mavenVersionStr = apiVersion.replaceAll(regex, Constants.BLANK_STRING);
        try {
            if (mavenVersionStr.contains(Constants.SYMBOL_POINT)) {
                /*如果包含.，则分割字符串，每个分割的长度为三位数，不足三位数前位填0，再拼接
                如 1.32.23 处理后的结果为1032023
                 */
                String[] versions = mavenVersionStr.split(Constants.REGEX_SYMBOL_POINT);
                StringBuilder jarVersionStr = new StringBuilder();
                for (String version : versions) {
                    jarVersionStr.append(fullVersion(version));
                }
                return Integer.parseInt(jarVersionStr.toString());
            } else {
                return Integer.parseInt(mavenVersionStr);
            }
        } catch (NumberFormatException e) {
            log.warn("convertJarVersion error", e);
            return 0;
        }
    }

    private static String fullVersion(String version) {
        //每位长度
        int perLength = 3;
        String full4Null = "000";
        if (StringUtils.isEmpty(version)) {return full4Null;}

        StringBuilder jarVersionStr = new StringBuilder(version);
        if (version.length() < perLength) {
            for(int i = 0; i < perLength - version.length(); i++) {
                jarVersionStr.insert(0, "0");
            }
        }
        return jarVersionStr.toString();
    }

    public static boolean validStringByReg(String target, String reg) {
        if (StringUtils.isEmpty(target)) {
            return false;
        }
        if (StringUtils.isEmpty(reg)) {
            return true;
        }
        Pattern pattern = regMap.computeIfAbsent(reg, p -> Pattern.compile(reg));
        return pattern.matcher(target).find();
    }
}
